<?php
#导出中奖记录
ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\model\MijiaSmartKitchen\MijiaSmartKitchenWinningRecord;
use Doraemon\service\User;
use Hhz\AdministrativeRegion\Region;

$list = MijiaSmartKitchenWinningRecord::dataSelect(['data_status' => MijiaSmartKitchenWinningRecord::STATUS_NORMAL]);

if ($list) {
    $uids = array_column($list, 'uid');
    $usersInfo = User::getBatchBasicUserInfo($uids);
    $usersInfoMap = !empty($usersInfo) ? array_column($usersInfo, null, 'uid') : [];

    $exportData = [];

    $platform = ['好好住App', '微信公众号'];

    foreach ($list as $item) {
        $row[0] = $item['uid'];
        $row[1] = $item['uid'] ? $usersInfoMap[$item['uid']]['nick'] : '';
        $row[2] = $item['third_id'];
        $row[3] = $item['prize_name'];
        $row[4] = $item['create_time'];
        $row[5] = $item['uname'];
        $row[6] = $item['phone'];
        $row[7] = getAddress($item['address']);
        $row[8] = $platform[$item['lottery_platform']];
        $exportData[] = $row;
    }

    $header = ['住友ID', '住友昵称', 'openID', '商品名称', '中奖时间', '姓名', '电话', '收货地址', '抽奖平台'];

    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();

    $titCol = 'A';
    foreach ($header as $key => $value) {
        // 单元格内容写入
        $sheet->setCellValue($titCol . '1', $value);
        $titCol++;
    }

    $sheet->getColumnDimension('A')->setWidth(15);
    $sheet->getColumnDimension('B')->setWidth(20);
    $sheet->getColumnDimension('C')->setWidth(30);
    $sheet->getColumnDimension('D')->setWidth(15);
    $sheet->getColumnDimension('E')->setWidth(15);
    $sheet->getColumnDimension('F')->setWidth(15);
    $sheet->getColumnDimension('G')->setWidth(15);
    $sheet->getColumnDimension('H')->setWidth(25);
    $sheet->getColumnDimension('I')->setWidth(15);

    $row = 2; // 从第二行开始

    foreach ($exportData as $item) {
        $dataCol = 'A';
        foreach ($item as $value) {
            // 单元格内容写入
            $sheet->setCellValue($dataCol . $row, $value);
            $dataCol++;
        }
        $row++;
    }

    $fileName = date('Ymd', time()) . '.xlsx';

    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');

    $writer->save('./' . $fileName);

}


function getAddress($address)
{
    if (empty($address)) {
        return '';
    }

    $addressArr = explode('|', $address);

    $areaArr = explode(',', $addressArr[0]);

    $province = Region::getNameByCode($areaArr[0]);

    $city = Region::getNameByCode($areaArr[1]);

    return $province . ' ' . $city . ' ' . $addressArr[1];
}